package com.onlygx.dva.web.base.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.http.HttpUtil;
import com.onlygx.dva.common.entity.common.RT;
import com.onlygx.dva.common.utils.FileInfoUtils;
import com.onlygx.dva.web.base.service.OSSService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * 版权所有 泰山信息技术有限公司
 *
 * @Author: 高祥
 */
@Api(tags = "FREE - 公共工具")
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/free/tools")
public class FreeToolsController {

    final OSSService ossService;

    /**
     * 上传单个文件
     */
    @ApiOperation("上传单个文件")
    @PostMapping("/upload_file")
    public RT<String> uploadFile(MultipartFile file) throws IOException {
        String path = ossService.pushFile(IdUtil.simpleUUID() + "." + FileUtil.getSuffix(file.getOriginalFilename()), file.getInputStream());
        return RT.success("上传成功",path);
    }

    /**
     * 网络文件下载 ，解决跨域下载
     */
    @ApiOperation(value = "网络文件下载",tags = "工具相关",notes = "下载网上的文件并在当前域名下返回文件流，用于网络文件下载，解决跨域问题")
    @GetMapping("/downloadWebFile")
    public void downloadWebFile(@ApiParam("文件绝对路径网址") @RequestParam String url, HttpServletRequest request, HttpServletResponse response){
        try {
            String rootPath = FileUtil.file(".", "/").getCanonicalPath();
            //System.out.println(rootPath);
            FileInfoUtils.createDir(rootPath);
            String filePath = rootPath + "/download/" + FileInfoUtils.getWebFileName(url);
            long size = HttpUtil.downloadFile(url, filePath);
            System.out.println("Download size: " + size);
            downFile(response,filePath);
            //return RT.success("下载成功");
        } catch (IOException e) {
            e.printStackTrace();
            //return RT.error(301,"下载失败！");
        }
    }

    /**
     * 相同名称网络文件下载 ，解决跨域下载
     */
    @ApiOperation(value = "相同名称网络文件下载",tags = "工具相关",notes = "下载网上的文件并在当前域名下返回文件流，用于相同名称网络文件下载，解决跨域问题")
    @GetMapping("/downloadSameNameWebFile")
    public void downloadSameNameWebFile(@ApiParam("文件绝对路径网址") @RequestParam String url, @ApiParam("文件名称") @RequestParam String fileName, HttpServletRequest request, HttpServletResponse response){
        try {
            String rootPath = FileUtil.file(".", "/").getCanonicalPath();
            FileInfoUtils.createDir(rootPath);
            byte[] fileNameBytes = fileName.getBytes(StandardCharsets.UTF_8);
            fileName = new String(fileNameBytes, 0, fileNameBytes.length, StandardCharsets.ISO_8859_1);
            String filePath = rootPath + "/download/" + fileName;
            long size = HttpUtil.downloadFile(url, filePath);
            System.out.println("Download size: " + size);
            downFile(response,filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载网络文件
     */
    @ApiOperation(value = "网络文件下载",tags = "工具相关",notes = "下载网上的文件输出到客户端")
    @GetMapping("/downloadFileFromUrl")
    public void downloadFileFromUrl(@ApiParam("文件网络网址") @RequestParam String url,
                                HttpServletResponse response) {
        try {
            String rootPath = FileUtil.file(".", "/").getCanonicalPath();
            FileInfoUtils.createDir(rootPath);
            String filePath = rootPath + "/download/";
            File downloadFile = HttpUtil.downloadFileFromUrl(url, filePath);
            outputStream(response,downloadFile,downloadFile.getName());
            log.info("下载文件：{}", url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void downFile(HttpServletResponse response, String realPath) throws IOException {
        if(!"".equals(realPath)){
            File file  = new File(realPath);
            if(file.exists()){
                outputStream(response,file,file.getName());
            }
        }
    }

    private void outputStream(HttpServletResponse response, File file,String fileName) throws IOException {
        InputStream in = new FileInputStream(file);
        //response.setContentType("image/jpeg");
        response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        response.addHeader("Content-Length", "" + file.length());
        OutputStream os = response.getOutputStream();
        byte[] b = new byte[1024];
        while( in.read(b)!= -1){
            os.write(b);
        }
        in.close();
        os.flush();
        os.close();
    }

    /**
     * 上传单个文件
     */
    @ApiOperation("上传单个文件")
    @PostMapping("/uploadGD_file")
    public RT<String> uploadGDFile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String path = ossService.pushFile(fileName.substring(0,fileName.lastIndexOf("."))+"_"+IdUtil.simpleUUID() + "." + FileUtil.getSuffix(file.getOriginalFilename()), file.getInputStream());
        return RT.success("上传成功",path);
    }
}
